<template>
  <component :is="component"></component>
</template>

<script>
import Vue from 'vue'
import coder from '@daelui/dogjs/dist/libs/coder.js'
import defaults from './default.js'

import * as Babel from '@babel/standalone'
const win = typeof self !== 'undefined' ? window : global
win.Babel = Babel

export default {
  props: {
    value: {
      type: Object,
      default () {
        return {
          code: defaults.code
        }
      }
    }
  },

  data () {
    return {
      component: 'div',
      isCompile: true
    }
  },

  watch: {
    value: {
      handler () {
        if (this.isCompile === false || String(this.isCompile) === '0') {
          return true
        }
        this.compile()
      },
      deep: true
    }
  },

  methods: {
    compile () {
      coder.vue.resolve(this.value.code || defaults.code, Vue, $pig).then(cp => {
        this.component = cp
      })
    }
  },

  created () {
    this.compile()
    this.emiter = () => {
      this.compile()
    }
    // 初始化编译状态
    this.$triggerEvent('init-is-compile', (value) => {
      this.isCompile = value
    })
  },

  mounted () {
    this.$bindEvent('compile-page-item', this.emiter)
    this.$bindEvent('update-is-compile', (value) => {
      this.isCompile = value
    })
  },

  beforeDestroy () {
    this.$unbindEvent('compile-page-item', this.emiter)
    this.$unbindEvent('update-is-compile')
  }
}
</script>

<style lang="less">
</style>
